//
//  QLMDeviceListVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/21.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMDeviceListVC.h"
#import "QLMDeviceDetailInfoVC.h"
#import "QLMDeviceListTabCell.h"
#import "QLMDeviceListModel.h"

#import "QLMAddDevicesVC.h"

@interface QLMDeviceListVC ()<UITableViewDelegate,UITableViewDataSource>{
    QLMDeviceListModel *deviceListModel;
    QLMCustomTipView *tipView;
    NSInteger currentPage;
}

@property (nonatomic,strong) UITableView *devicetableview;

@end

@implementation QLMDeviceListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"设备管理";
    
    currentPage=1;
    
    deviceListModel=[[QLMDeviceListModel alloc] init];
    deviceListModel.list=[NSMutableArray array];
    
    CGRect tabFrame = CGRectMake(0, 0, kScreen_width, kScreen_height-40-QLM_StatusBarAndNavigationBarHeight-IOS11_OR_LATER_SPACE(34));
    
    _devicetableview=[[UITableView alloc] initWithFrame:tabFrame style:UITableViewStyleGrouped];
    _devicetableview.backgroundColor=[UIColor clearColor];
    _devicetableview.delegate=self;
    _devicetableview.dataSource=self;
    _devicetableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    _devicetableview.showsVerticalScrollIndicator=NO;
    _devicetableview.showsHorizontalScrollIndicator=NO;
    _devicetableview.tableFooterView=[UIView new];
    [self.view addSubview:_devicetableview];
    
    //上拉刷新
    _devicetableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    _devicetableview.mj_footer.automaticallyHidden = YES;
    
    tipView=[QLMCustomTipView sharedInstance];
    tipView.hidden = YES;
    [_devicetableview addSubview:tipView];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, kScreen_height-40-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 40);
    [rightButton addTarget:self action:@selector(addButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"+新增设备" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    rightButton.backgroundColor=kButtonColor;
    [self.view addSubview:rightButton];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    [self requestData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [deviceListModel.list removeAllObjects];
    currentPage=1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addButtonAction{
    QLMAddDevicesVC *addDevicesVC=[QLMAddDevicesVC new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:addDevicesVC animated:YES];
}

- (void)requestData{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:[NSString stringWithFormat:@"%ld",(long)currentPage] forKey:@"page"];
    [paramerDic setObject:@"10" forKey:@"rows"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/equipmentManager" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        
                        [self.view hideToastActivity];
                        [_devicetableview.mj_footer endRefreshing];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            [deviceListModel.list addObjectsFromArray:responseObject[@"list"]];

                            if (deviceListModel.list.count==0){
                                tipView.hidden = NO;
                            }else{
                                if ([responseObject[@"list"] count]<10) {
                                    _devicetableview.mj_footer.state = MJRefreshStateNoMoreData;
                                }
                                tipView.hidden = YES;
                                currentPage++;
                            }
                            [_devicetableview reloadData];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                        
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                        [_devicetableview.mj_footer endRefreshing];
                    }
     ];
}

- (void)_deleteDeviceData:(NSMutableArray *)rowsArray{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    
    QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[[rowsArray[0] integerValue]] error:nil];
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:deviceInfoModel.equipmentId forKey:@"ids"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/equipmentManager/delete" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                        
                            [deviceListModel.list removeObjectAtIndex:[rowsArray[0] integerValue]];
                            [_devicetableview reloadData];
                            
                            if (deviceListModel.list.count==0) {
                                tipView.hidden = NO;
                            }else{
                                tipView.hidden = YES;
                            }
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (UIButton *)acreatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor whiteColor];
    newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    [newButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    newButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);

    return newButton;
}

- (void)editButtonAction:(UIButton *)btn{
    
    if (btn.tag>9809) {//编辑
        
        QLMAddDevicesVC *addDevicesVC=[QLMAddDevicesVC new];
        if (deviceListModel.list.count!=0) {
            QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[btn.tag-9810] error:nil];
            addDevicesVC.deviceInfoModel=deviceInfoModel;
            addDevicesVC.isCanEnableEdit=YES;
        }
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:addDevicesVC animated:YES];
        
    }else{//删除
        NSIndexPath *aindexPath = [NSIndexPath indexPathForRow:0 inSection:(btn.tag-8810)];
        [self deleteDeviceAlert:aindexPath];
    }
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(deviceListModel.list.count == 0){
        return 0.1;
    }
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor whiteColor];
    if(deviceListModel.list.count != 0){
        UIButton *editBtn=[self acreatButton:CGRectMake(kScreen_width-20-60-60-10, 0, 60, 30) title:@"编辑" image:@"edit"];
        editBtn.tag=9810+section;
        [headerView addSubview:editBtn];
        
        UIButton *deleteBtn=[self acreatButton:CGRectMake(kScreen_width-20-60, 0, 60, 30) title:@"删除" image:@"delet"];
        deleteBtn.tag=8810+section;
        [headerView addSubview:deleteBtn];
        
        UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0, 29.6, kScreen_width, 0.4)];
        lineView.backgroundColor=[UIColor lightGrayColor];
//        [headerView addSubview:lineView];
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==deviceListModel.list.count-1) {
        return 0.1;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return deviceListModel.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QLMDeviceListTabCell *cell=[QLMDeviceListTabCell cellWithTableView:tableView];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    if (deviceListModel.list.count!=0) {
        QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[indexPath.section] error:nil];
        
        cell.devicenameLabel.text=[NSString stringWithFormat:@"设备：%@%@",deviceInfoModel.brandName,deviceInfoModel.modelName];
        
        NSString *otherName=nil;
        if (deviceInfoModel.alias.length==0) {
            otherName=@"无";
        }else{
            otherName=deviceInfoModel.alias;
        }
        cell.othernameLabel.text=[NSString stringWithFormat:@"别名：%@",otherName];
        
        if (deviceInfoModel.serialNo.length==0) {
            cell.seriNoLab.text=@"机号：无";
        }else{
            cell.seriNoLab.text=[NSString stringWithFormat:@"机号：%@",deviceInfoModel.serialNo];
        }
        
        cell.statusNumLabel.hidden=YES;
    }
    
    return cell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[indexPath.section] error:nil];
    if (self.isCannotEdit) {
        NSString *deviceNameStr = [NSString stringWithFormat:@"%@%@",deviceInfoModel.brandName,deviceInfoModel.modelName];
        self.block(deviceInfoModel.equipmentId, deviceInfoModel.modelId, deviceInfoModel.machineId,deviceNameStr);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        QLMDeviceDetailInfoVC *deviceInfoVC=[QLMDeviceDetailInfoVC new];
        deviceInfoVC.deviceInfoModel=deviceInfoModel;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:deviceInfoVC animated:YES];
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {//删除
        [self deleteDeviceAlert:indexPath];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (void)deleteDeviceAlert:(NSIndexPath *)indexPath{
    
    QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[indexPath.section] error:nil];
    if ([deviceInfoModel.unfinishedOrder integerValue]!=0) {
        ETToast(@"当前设备已有订单不可删除！");
        return;
    }
    
//    __weak QLMDeviceListVC *weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定删除设备？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self commitClick:indexPath];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)commitClick:(NSIndexPath *)indexPath{
    NSIndexPath *aindexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
    [_devicetableview selectRowAtIndexPath:aindexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    [self _deleteDeviceData:[NSMutableArray arrayWithObjects:@(indexPath.section),nil]];
}

@end
